package com.jyw.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.jyw.App;
import com.jyw.R;
import com.jyw.activity.BannerShowActivity;
import com.jyw.activity.GaoDuanActivity;
import com.jyw.activity.KefuActivity;
import com.jyw.activity.LocationActivity;
import com.jyw.activity.ServiceAreaActivity;
import com.jyw.activity.ServiceIntroductionActivity;
import com.jyw.activity.XxActivity;
import com.jyw.activity.XyjfActivity;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.AllClass;
import com.jyw.pojo.EventBusTypes;
import com.jyw.service.GeTuiPushService;
import com.jyw.service.GetIntentService;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/1
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {
    private List<String> sImages;
    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();

    private TextView tvLocationCity;
    private View mContentView;
    private ImageView ivKefu, ivLocation;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // com.getui.demo.DemoPushService 为第三方自定义推送服务
        PushManager.getInstance().initialize(getActivity().getApplicationContext(), GeTuiPushService.class);

        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(getActivity().getApplicationContext(), GetIntentService.class);
    }

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return mContentView = LayoutInflater.from(getActivity()).inflate(R.layout.fgt_home, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sImages = new ArrayList<>();

        loadData();

        mContentView.findViewById(R.id.iv_0).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(getActivity(), XyjfActivity.class));
                    }
                });

        mContentView.findViewById(R.id.iv_1).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(getActivity(), XxActivity.class));
                    }
                });

        mContentView.findViewById(R.id.iv_2).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), GaoDuanActivity.class);
                        intent.putExtra("TAB_NUM", 0);
                        startActivity(intent);
                    }
                });

        mContentView.findViewById(R.id.iv_3).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), GaoDuanActivity.class);
                        intent.putExtra("TAB_NUM", 1);
                        startActivity(intent);
                    }
                });

        mContentView.findViewById(R.id.iv_4).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ServiceIntroductionActivity.class);
                        startActivity(intent);
                    }
                });

        mContentView.findViewById(R.id.iv_5).

                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ServiceAreaActivity.class);
                        startActivity(intent);
                    }
                });

        tvLocationCity = (TextView) mContentView.findViewById(R.id.tv_location_city);
        ivKefu = (ImageView) mContentView.findViewById(R.id.iv_kefu);
        ivLocation = (ImageView) mContentView.findViewById(R.id.iv_location);
        ivKefu.setOnClickListener(this);
        ivLocation.setOnClickListener(this);
        tvLocationCity.setOnClickListener(this);


        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            locate();
        } else {
            EasyPermissions.requestPermissions(getActivity(), "用于百度地图定位的权限申请",
                    101, perms);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        locate();
    }

    private void locate() {
        String str = getPrefs().getString("cityLocation", "");
        if (!str.equals("")) {
            tvLocationCity.setText(str);
        } else {
            mLocationClient = new LocationClient(getActivity());
            mLocationClient.registerLocationListener(myListener);

            setLocationOption();
            mLocationClient.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        EventBus.getDefault().unregister(this);
    }

    private void onClickLocation() {
        startActivity(new Intent(getActivity(), LocationActivity.class));
    }

    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            tvLocationCity.setText(location.getCity());
            getPrefs().edit().putString("cityLocation", location.getCity()).apply();
            mLocationClient.stop();
        }
    }


    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); //打开gps
        option.setServiceName("com.baidu.location.service_v2.9");
        /*option.setPoiExtraInfo(true);*/
        option.setAddrType("all");
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setPriority(LocationClientOption.GpsFirst);       //gps
        /*option.setPoiNumber(10);*/
        option.disableCache(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_kefu:
                startActivity(new Intent(getActivity(), KefuActivity.class));
                break;
            case R.id.iv_location:
                onClickLocation();
                break;
            case R.id.tv_location_city:
                onClickLocation();
                break;
        }
    }


    private void loadData() {
        Request request = new Request.Builder().
                url(Server.ALL_CLASS).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(getActivity(), "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONArray arr;
                final List<AllClass.Banner> banners = new ArrayList<>();
                List<AllClass.Class> classes = new ArrayList<>();
                try {
                    arr = new JSONArray(response.body().string());
                    JSONArray classesJArray = (JSONArray) arr.get(0);
                    JSONArray bannersJArray = (JSONArray) arr.get(1);
                    Gson gson = new Gson();
                    for (int i = 0; i < bannersJArray.length(); i++) {
                        banners.add(gson.fromJson(bannersJArray.get(i).toString(), AllClass.Banner.class));
                    }
                    for (int i = 0; i < classesJArray.length(); i++) {
                        classes.add(gson.fromJson(classesJArray.get(i).toString(), AllClass.Class.class));
                    }
                    App.parent1s.clear();
                    App.parent2s.clear();
                    App.parent3s.clear();
                    App.parent4s.clear();
                    App.parent5s.clear();
                    App.parent6s.clear();
                    App.parent7s.clear();
                    App.parent8s.clear();
                    for (AllClass.Class c : classes) {
                        if (c.getId().equals("1")) {
                            App.parent1 = c;
                        } else if (c.getId().equals("2")) {
                            App.parent2 = c;
                        } else if (c.getId().equals("3")) {
                            App.parent3 = c;
                        } else if (c.getId().equals("4")) {
                            App.parent4 = c;
                        } else if (c.getId().equals("5")) {
                            App.parent5 = c;
                        } else if (c.getId().equals("6")) {
                            App.parent6 = c;
                        } else if (c.getId().equals("7")) {
                            App.parent7 = c;
                        } else if (c.getId().equals("8")) {
                            App.parent8 = c;
                        } else {
                            if (c.getParent().equals("1")) {
                                App.parent1s.add(c);
                            } else if (c.getParent().equals("2")) {
                                App.parent2s.add(c);
                            } else if (c.getParent().equals("3")) {
                                App.parent3s.add(c);
                            } else if (c.getParent().equals("4")) {
                                App.parent4s.add(c);
                            } else if (c.getParent().equals("5")) {
                                App.parent5s.add(c);
                            } else if (c.getParent().equals("6")) {
                                App.parent6s.add(c);
                            } else if (c.getParent().equals("7")) {
                                App.parent7s.add(c);
                            } else if (c.getParent().equals("8")) {
                                App.parent8s.add(c);
                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                for (AllClass.Banner b : banners) {
                    sImages.add(b.getImg());
                }

                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Banner banner = (Banner) mContentView.findViewById(R.id.banner);
                        banner.setDelayTime(4000);
                        banner.setImageLoader(new PicassoImageLoader()).
                                setBannerStyle(BannerConfig.CIRCLE_INDICATOR).
                                setIndicatorGravity(BannerConfig.CENTER).setImages(sImages).start();
                        banner.setOnBannerClickListener(new OnBannerClickListener() {
                            @Override
                            public void OnBannerClick(int i) {
                                i = i - 1;
                                Intent intent = new Intent(getActivity(), BannerShowActivity.class);
                                intent.putExtra("url", banners.get(i).getUrl());
                                startActivity(intent);
                            }
                        });
                    }
                }.execute();
            }
        });
    }

    private class PicassoImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Picasso.with(context).load((String) path).into(imageView);
        }
    }

    public void onEventMainThread(EventBusTypes.Base type) {
        if (type instanceof EventBusTypes.RefreshLocationCity) {
            String city = ((EventBusTypes.RefreshLocationCity) type).city;
            tvLocationCity.setText(city);
            getPrefs().edit().putString("cityLocation", city).apply();
        } else if (type instanceof EventBusTypes.ObtainClientId) {
            getPrefs().edit().putString("client_id", ((EventBusTypes.ObtainClientId) type).cid).apply();
        }
    }

}
